package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import persistent.MigratorServer;

public class InstructionsListener extends Thread{
	
	private static final int PORT_INSTR = 5230;
	
	protected boolean active;
	
	protected ServerSocket serverSocket;
	
	private FramesServer framesServer;
	private AlertsServer alertsServer;
	
	public InstructionsListener(FramesServer framesServer, AlertsServer alertsServer) throws IOException{
		
		active = true;
		
		this.framesServer = framesServer;
		this.alertsServer = alertsServer;
		
		serverSocket = new ServerSocket(PORT_INSTR);
	}
	
	public void run(){
		
		while(active){
			
			try{
				Socket instrSocket = serverSocket.accept();
				ObjectInputStream ois = new ObjectInputStream(instrSocket.getInputStream());
				String instruction = (String)ois.readObject();
				
				if(instruction.equals("resume")){
					framesServer.resumeServer();
					alertsServer.resumeServer();
				}
				else if(instruction.equals("suspend")){
					framesServer.suspendServer();
					alertsServer.suspendServer();
				}
				else if(instruction.equals("migrate")){
					new MigratorServer().start();
				}
				
				instrSocket.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
				
		}
			
	}

}
